package com.hiwhitley.himei.module.meitu;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.design.widget.AppBarLayout;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.animation.DecelerateInterpolator;
import android.widget.Toast;

import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.hiwhitley.himei.R;
import com.hiwhitley.himei.app.base.BaseActivity;
import com.hiwhitley.himei.utils.DownLoadUtil;
import com.hiwhitley.himei.utils.FileUtil;
import com.hiwhitley.himei.utils.StrUtil;
import com.hiwhitley.himei.widget.glide.GlideImageView;

import java.io.File;
import java.io.FileNotFoundException;

import butterknife.BindView;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import uk.co.senab.photoview.PhotoViewAttacher;

import static com.hiwhitley.himei.R.id.toolbar;

/**
 * Created by hiwhitley on 2016/9/22.
 */

public class PhotoActivity extends BaseActivity {

    public static final String KEY_IMG_URL = "image_url";
    public static final String TRANSIT_PIC = "picture";
    private static final String TAG = "PhotoActivity";

    @BindView(R.id.iv_photo)
    GlideImageView mIvPhoto;
    @BindView(toolbar)
    Toolbar mToolbar;
    @BindView(R.id.app_bar_layout)
    AppBarLayout mAppBarLayout;
    @BindView(R.id.bottom_navigation_bar)
    BottomNavigationBar mBottomNavigationBar;

    private String mImageUrl;
    private boolean mIsHidden = false;
    private PhotoViewAttacher mPhotoViewAttacher;
    private FileUtil fileUtil;
    private MediaScannerConnection connection;

    public static Intent newIntent(Context context, String url) {
        Intent intent = new Intent(context, PhotoActivity.class);
        intent.putExtra(PhotoActivity.KEY_IMG_URL, url);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        return intent;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_photo;
    }

    @Override
    protected void init() {

        mImageUrl = getIntent().getStringExtra(KEY_IMG_URL);
        ViewCompat.setTransitionName(mIvPhoto, TRANSIT_PIC);
        mIvPhoto.loadNetImage(mImageUrl, R.drawable.bg_holder_brown);
        fileUtil = new FileUtil(this);

        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);

        setColor(this, getResources().getColor(R.color.md_black));
    }

    @Override
    protected void setListeners() {

        mPhotoViewAttacher = new PhotoViewAttacher(mIvPhoto);
        mPhotoViewAttacher.setOnViewTapListener((view, v, v1) -> hideOrShowToolbar());

        mBottomNavigationBar.setMode(BottomNavigationBar.MODE_FIXED);
        mBottomNavigationBar.setBarBackgroundColor(R.color.md_black);
        mBottomNavigationBar.setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_STATIC)
                .addItem(new BottomNavigationItem(R.drawable.ic_action_wallpaper, "设为壁纸").setActiveColorResource(R.color.red))
                .setFirstSelectedPosition(-1)
                .initialise();

        hideOrShowToolbar();

        Toast toast = Toast.makeText(this, "设置壁纸成功", Toast.LENGTH_SHORT);

        mBottomNavigationBar.setTabSelectedListener(new BottomNavigationBar.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int position) {
                switch (position) {
                    case 0:
                        try {
                            Log.d(TAG, "onTabSelected" + position);
                            setWallpaper(((BitmapDrawable) mIvPhoto.getDrawable()).getBitmap());
                            toast.show();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                }

            }

            @Override
            public void onTabUnselected(int position) {

            }

            @Override
            public void onTabReselected(int position) {

            }
        });
    }

    private void hideOrShowToolbar() {
        mAppBarLayout.animate()
                .translationY(mIsHidden ? 0 : -mAppBarLayout.getHeight())
                .setInterpolator(new DecelerateInterpolator(2))
                .start();
        mBottomNavigationBar.animate()
                .translationY(mIsHidden ? 0 : mBottomNavigationBar.getHeight())
                .setInterpolator(new DecelerateInterpolator(2))
                .start();
        mIsHidden = !mIsHidden;
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_photo, menu);
        return true;
    }


    private void saveImageToGallery() {
        Observable.just(mImageUrl).flatMap(new Func1<String, Observable<Boolean>>() {
            @Override
            public Observable<Boolean> call(String s) {
                File file = fileUtil.getDiskCacheDir(StrUtil.getMD5(s) + ".jpg");
                boolean isSuccess = new DownLoadUtil().download(s, file);
                if (isSuccess) {
                    try {
                        MediaStore.Images.Media.insertImage(getContentResolver(),
                                file.getPath(), null, null);
                        connection = new MediaScannerConnection(PhotoActivity.this, new MediaScannerUtil(file.getPath()));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                return Observable.just(isSuccess);
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    private Subscriber<Boolean> subscriber = new Subscriber<Boolean>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {
            Toast.makeText(PhotoActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNext(Boolean isSuccess) {
            if (isSuccess) {
                Toast.makeText(PhotoActivity.this, "下载成功" , Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(PhotoActivity.this, "下载失败", Toast.LENGTH_SHORT).show();
            }
        }
    };

    private class MediaScannerUtil implements MediaScannerConnection.MediaScannerConnectionClient {
        private String mPath;

        public MediaScannerUtil(String path) {
            mPath = path;
        }

        @Override
        public void onMediaScannerConnected() {
            connection.scanFile(mPath, "image/jpg");
        }

        @Override
        public void onScanCompleted(String path, Uri uri) {
            connection.disconnect();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.action_save:
                saveImageToGallery();
                return true;
            case android.R.id.home:
                onBackPressed();
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPhotoViewAttacher.cleanup();
    }
}
